// parser.js
import _ from "lodash";
import fs from 'fs';

// Example usage
const text = fs.readFileSync("e:\\game\\ex1\\mission.scn").toString();

var index = 0;

function preProcess(obj: any) {
    var s = "";
    var subObjs = [];
    var isStr = false;
    while (true) {
        var c = text[index++];
        if (index > text.length) {
            obj.s = s.trim();
            obj.subObjs = subObjs;
            return;
        }
        if (isStr) {
            if (c == "\"") {
                isStr = false;
            }
            s += c;
        } else {
            if (c == "{") {
                var subObj = {};
                preProcess(subObj);
                subObjs.push(subObj);
            }
            else if (c == "}") {
                obj.s = s.trim();
                obj.subObjs = subObjs;
                return;
            }
            else if (c == "\"") {
                isStr = true;
                s += c;
            } else {
                s += c;
            }
        }
    }
}

function proc(obj: any) {
    var ret: any[] = [];
    function splitWithQuotes(str: any) {
        const regex = /"[^"]*"|'[^']*'|\S+/g;
        const result = [];
        let match;
        while ((match = regex.exec(str)) !== null) {
            result.push(match[0]);
        }
        return result;
    }
    var list = splitWithQuotes(obj.s);
    list.forEach((item) => {
        ret.push(item);
    });
    obj.subObjs.forEach((item: any) => {
        ret.push(proc(item));
    });
    return ret;
}

(() => {

    var obj = {};
    preProcess(obj);

    obj = proc(obj);

    var flg = false;
    var filter = (obj: any) => {
        obj.forEach((item: any, index: number) => {
            if (_.isString(item)) {
                if (index >= 3) {
                    if (["Orientation", "Position", "xform", "wall"].indexOf(obj[0]) < 0) {
                        flg = true; console.log(obj);
                    }
                }
            } else {
                filter(item);
            }
        });
    };

    //filter(obj);
    console.log(JSON.stringify(obj, null, 2));
})();

// Optional: Write to file
// fs.writeFileSync('output.json', JSON.stringify(parsed, null, 2));
